#include "handy/handy/handy.h"
#include <algorithm>
#include <stdio.h>
#include <string>
#include <stdint.h>
#include <arpa/inet.h>
#include <sstream>
#include <vector>
#include "xudp.pb.h"
#include "common.h"
using namespace std;
using namespace handy;
int g_una = 0;
void handle_package(xpackage& p) {
	if (p.cmd() == CMD_DATA) {
		//info("size:%d\n", p.msg_size());
		vector<int> msg_id;
		for (int i = 0; i < p.msg_size(); i++) {
			const xmsg m = p.msg(i);
			msg_id.push_back(m.id());
		}
		std::sort(msg_id.begin(), msg_id.end());
		stringstream ss;
		for(int i = 0; i < (int)msg_id.size();i++){
			ss << msg_id[i]<<"_";
		}

		info("una:%d,msg:%s", g_una, ss.str().c_str());

		for (auto id : msg_id) {
			if (id > g_una){
				fatal("something wrong:%d_%d", id, g_una);
			}
			if (id == g_una) {
				info("id:%d,time:%ld", id,util::timeMilli());
				g_una++;
			}
		}
	}
}
int main() {
	setloglevel("INFO");
  	setlogfile("test_server_full_udp");
	EventBase base;
	Signal::signal(SIGINT, [&] { base.exit(); });

	UdpServerPtr s = handy::UdpServer::startServer(&base, "", SERVER_PORT);
	exitif(s == NULL, "start udp server failed");

	s->onMsg([](const UdpServerPtr& p, Buffer buf, Ip4Addr peer) {
		xpackage package;
		bool s = package.ParseFromArray(buf.data(), buf.size());
		if (s) {
			handle_package(package);
		}
		xpackage rsp;
		rsp.set_cmd(CMD_ACK);
		rsp.set_una(g_una);
		char b[500];
		s = rsp.SerializeToArray(b, sizeof(b));
		if (!s) {
			fatal("serilize failed");
		}
		p->sendTo(b, rsp.ByteSize(), peer);
	});

	base.loop();
	info("program exited");
}
